package com.tydic.common.security.config;

import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.hutool.core.util.ArrayUtil;
import com.tydic.common.core.utils.ServletUtils;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SaTokenConfigure {
    /**
     * 重写 Sa-Token 框架内部算法策略
     */
    @PostConstruct
    public void rewriteSaStrategy() {
        // 重写 Token 生成策略
        SaStrategy.instance.createToken = (loginId, loginType) -> {
            HttpServletRequest request = ServletUtils.getRequest();
            Cookie[] cookies = request.getCookies();
            if (ArrayUtil.isNotEmpty(cookies)) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("sessionid")) {
                        return cookie.getValue();
                    }
                }
            }
            return SaFoxUtil.getRandomString(60);    // 随机60位长度字符串
        };
    }
}
